package com.flying.ouyu;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

import com.flying.client.network.NetworkProvider;
import com.flying.client.utils.Logger;
import com.flying.ouyu.net.NetworkProxy;
import com.flying.ouyu.net.NetworkSink;

import android.app.Application;
import android.net.Proxy;
import android.os.Handler;

/**
 * @author flying
 * @version 1.0
 */
public class OuyuApplication extends Application {
	
	private static Logger logger = Logger.getLogger(OuyuApplication.class.getName());;
	private static OuyuApplication _instance;
	/**
	 * create a threadpool's executor
	 */
	private final ScheduledThreadPoolExecutor coreThreadPool = new ScheduledThreadPoolExecutor(3, new ThreadFactory(){
		final AtomicInteger idMaker = new AtomicInteger(1024);
		
		public Thread newThread(Runnable r) {
			logger.debug("newThread id="+idMaker.getAndIncrement());
			return new Thread(r,"core-executor"+idMaker.getAndIncrement());
		}
	});
	/**
	 * create the application handler
	 */
	private final Handler coreHandler = new Handler();
	
	private Thread mainThread = null;
	/**
	 * Get the application singleton object
	 * @return
	 */
	public static OuyuApplication getInstance()
	{
		return _instance;
	}
	
	@Override
	public void onCreate()
	{
		super.onCreate();
		
		//初始化日志配置
		Logger.init(Logger.LOGLEVEL_DEBUG, "ouyu", true);
		
		logger.debug("onCreate");
		
		//TODO:init the application data
		init();
		
		NetworkProxy.getInstance().init();
		
	}
	/**
	 * Init the application data
	 */
	private void init()
	{
		_instance = this;
		mainThread = Thread.currentThread();
	}
	
	/**
	 * Get the application's handler
	 * @return
	 */
	public Handler getHandler()
	{
		return coreHandler;
	}
	/**
	 * Get the application's ThreadPoolExecutor
	 * @return
	 */
	public ScheduledThreadPoolExecutor getExecutor()
	{
		return coreThreadPool;
	}
	
	/**
	 * Check whether the current thread is Main thread
	 * @return
	 */
	public boolean isInMainThread() {
		return Thread.currentThread() == this.mainThread;
	}
}
